const path = require('path');
const fs = require('fs')

let port = 3000
const cwd = process.cwd().replace(/\\/g, '/')
const isSubPackage = cwd.includes('/packages/')
let subPackageName = null;
const proxyOptions = {}

if (process.env.NODE_ENV === 'development') {
  const dirs = fs.readdirSync(__dirname + '/packages/')
  const packageDevPortMap = {}
  let subPackagePort = 3000
  dirs.forEach(dir => {
    subPackagePort = subPackagePort + 1
    packageDevPortMap[dir] = subPackagePort
  });

  if (isSubPackage) {
    subPackageName = cwd.split('/').pop()
    port = packageDevPortMap[subPackageName]
  } else if (process.env.DEV_PACKAGES) {
    const devPackages = process.env.DEV_PACKAGES.split(',')
    devPackages.forEach(packageName => {
      if (packageDevPortMap[packageName]) {
        let path = `/subContent/platform/${packageName}/`
        proxyOptions[path] = {
          target: `http://localhost:${packageDevPortMap[packageName]}/`,
          pathRewrite: { '/subContent/platform/': '' },
        }
      }
    })

    console.log('proxyOptions', proxyOptions)
  }
}

module.exports = {
  publicPath: isSubPackage ? `/${subPackageName}/` : '/new/',
  lintOnSave: false,
  filenameHashing: false,
  css: {
    extract: false,
  },
  configureWebpack: {
    resolve: {
      extensions: ['.js', '.json', '.vue'],
      alias: {
        '@': path.resolve(cwd, 'src/'),
        '@lib': path.resolve(__dirname, 'packages/_lib/'),
      },
    },
    externals: { // 以下包使用 cdn 引入不打包到子项目，（如果有使用自己特定版本把下面的删除就可以了）
      'vue': 'Vue',
      'vue-router': 'VueRouter',
      'ant-design-vue': 'antd',
      '$': 'jQuery',
      'jsoneditor': 'JSONEditor',
      '@vue/composition-api': 'VueCompositionAPI',
    }
  },
  chainWebpack: (config) => {
    config.optimization.delete('splitChunks');

    // config
    //   .plugin('webpack-bundle-analyzer')
    //   .use(new (require('webpack-bundle-analyzer').BundleAnalyzerPlugin)({
    //     analyzerPort: 8889,
    //   }));
  },
  devServer: {
    port: port,
    historyApiFallback: true,
    disableHostCheck: true,
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    setup: function(app) {
      if (isSubPackage) {
        app.get(`/${subPackageName}/*`, function(req, res, next) {
          console.log('req.url', req.url)
          if (path.extname(req.url) === '') {
            req.url = `/${subPackageName}/index.html`
          }
          next()
        });
      }
    },
    proxy: {
      ...proxyOptions,
      '/api': {
        target: 'http://platformtest2.tlwok.com/',
        changeOrigin: true,
        pathRewrite: { '^/api/': '' },
        // bypass: function (req, res, proxyOptions) {
        //   if (req.url === '/new' || req.url === '/') {
        //     return req.url
        //   }
        // },
        headers: {
          referer: 'http://platformtest2.tlwok.com/new/',
          cookie: 'logoImg="https://file.tlwok.com/group1/M00/04/9D/CgsWD10CC-GAPwJSAAA5yR3ctto342.png"; headAds="https://file.tlwok.com/group1/M00/05/AD/CgsXD105VVCAV_ltAABcgHSjxxw000.jpg"; activityLogoImg=/resources/v1/images/temp/logo.png; activityheadAds=""; UM_distinctid=17607c965da38b-03f02ac6f3dd1c-5a30124a-1fa400-17607c965dbbfc; Hm_lvt_41692f706732a07ee67b617bd4a5070d=1605246002,1605604477,1606098308,1606448319; Hm_lpvt_41692f706732a07ee67b617bd4a5070d=1606448408; _ecc_b2b_=506B5A2CF4487AB42022AEE69ED33A6F0A0EE1B38967F8C01CDA36BC6A282EF743A79D4ED44F2ECA321F8C9637A0354BDD50EEC55B466440FD27AB45D6969F675768035C6FB88006CAA5BC28F2BB3D8A140BF85519383817B5A65377B34729E47A47469D684AD90214AAABFC22520D846BAA0B6B1280FB324A0A52F13644ED4D5AD65F41F966EC0DEE10E0AA60ED72A6E917D94D867CB7F3BCFFB4B8A71EE39C536A0DC582BB092D1CA5E884AC8E1DDCC5B14EEDA9D3E11B22DBB58EED697A399B05D5FED30490E27EAA0E2BF30D72F0169D326964D4A0C64FDF5FA95E01EF8BB8CE08D6A56837F2C95247E4C0EE28F0E090AA0A945A46FEC118BDDB812CF80E3B29B1A0BE47E5D93F41FE1B48025098; _ecc_sid_=075A42AD86CA942C12B917BC20EAB12A4EF3232A20577858DB2DAE26349577C4440BA92A7BF84DDB477E3D7E048670DC0DED656CF2200546713A5D1474241054DAA98D8EF8E1E2822FC24704D80B5D0AAFF9AED098DA3A861930E595DB3E9525DD33E8EBD766011B5840266F4F9AEAD3DC7A999F19FE039DA882D729CDE5747EBF38AD11BFD2C169BB4CE96C4A98AE22721A382C7C5A7351BDC9C6B58F82ADA069D56D9FD9F8666EA0E4991664C04C7097FDB5D2F36EEFC505F7885F588072800D3E247D4B6E80CE94F8C28784E58A80C5C9B96E7CDE960BC9B264B133DBC3EBAD8DC0A6F5EDD047E877F4D9164941E8DCBE619917DFDC26AEB980440DEE48F2FC020AF88A77177F38A9D9695BBD215E3488F6ABD648DF60D931B9084129D203DEC931482573C98C0A0F81FB22034C3FE90148DA5CC272277E0B4B082211155DE98F82EE8D152FA85A5D4E31BA0479BC0B3F06DCEE9EC671F1208EAFB3B9756C9C97CA3ECE6061AA81FC0650B4FE5A2FC34679FC31F93C3BFDB83F71CC97A2F79B6EBA80D9AC32ABFB423517C4A369AE51D2AED7B934C9BB82ADE104FA34EDF1B490082B3EC079130B6595060178EC64B83ED7D4C84F630ED647A2FEA422C01A0D76DBF44C7D77E01E99663AC9C306C71B6C2642E41A8379986C493659EA4F17C39C3EFAFAB1AC5C201ACF1821E150CE69750FD4553BD6CAE84C972E1C36B9E337F36D2488FED1E1872DE69E2E8B89CB0E1849BCAB319E56CB780196ED37E57587B352A2660A4EAC5FA5A23FC3D43C729989B4763AF2699EE0D87B0E7A86F3AF0752B1A9BF49417274988487BECF0925; __jda=86320733.16064543448111984094806.1606454345.1606454345.1606454345.1; __jdb=86320733.1.16064543448111984094806%7C1.1606454345; __jdv=86320733%7Cdirect%7C-%7Cnone%7C-%7C1606454344811; __jdc=86320733'
        },
      },
    }
  }
}
